package com.dianrui.moonfire.activity;

import android.content.Intent;
import android.os.Bundle;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.View;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.alipay.sdk.app.PayTask;
import com.blankj.utilcode.util.SPUtils;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chad.library.adapter.base.BaseViewHolder;
import com.dianrui.moonfire.Constant;
import com.dianrui.moonfire.R;
import com.dianrui.moonfire.adapter.TopUpAdapter;
import com.dianrui.moonfire.alipay.PayResult;
import com.dianrui.moonfire.bean.TopUp;
import com.dianrui.moonfire.util.EventBusConstants;
import com.dianrui.moonfire.util.JsonUtils;
import com.dianrui.moonfire.util.MyUtil;
import com.dianrui.moonfire.okhttp.XHttpRequest;
import com.dianrui.moonfire.util.StringUtils;
import com.dianrui.moonfire.util.ToastUtil;
import com.dianrui.moonfire.util.Url;
import com.google.gson.JsonObject;
import com.google.gson.reflect.TypeToken;
import com.tencent.mm.opensdk.modelpay.PayReq;
import com.tencent.mm.opensdk.openapi.IWXAPI;
import com.tencent.mm.opensdk.openapi.WXAPIFactory;

import org.greenrobot.eventbus.EventBus;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import butterknife.BindView;
import butterknife.OnClick;

/**
 * Description:充值
 * User: luoziyin
 * Date: 2020-8-17
 */
@SuppressWarnings("ALL")
public class RechargeActivity extends BaseActivity {
    private String money;
    private String type;
    private TopUpAdapter topUpAdapter;
    private List<TopUp> topUpList = new ArrayList<>();
    private int currentPosition = 0;


    @BindView(R.id.title)
    TextView title;
    @BindView(R.id.cb_zfb)
    CheckBox cbZfb;
    @BindView(R.id.cb_wx)
    CheckBox cbWx;
    @BindView(R.id.editText)
    TextView rechageMoney;
    @BindView(R.id.recyclerView)
    RecyclerView mRecyclerView;



    @Override
    public int getContentViewId() {
        return R.layout.activity_recharge;
    }

    @Override
    public void initView() {
        customInit(true);
        title.setText(getResources().getString(R.string.recharge_title));
        getTopUp();
        mRecyclerView.setLayoutManager(new GridLayoutManager(this, 3));
        topUpAdapter = new TopUpAdapter(this, topUpList);
        mRecyclerView.setAdapter(topUpAdapter);
        mRecyclerView.setHasFixedSize(true);

        topUpAdapter.setOnItemClickListener(new BaseQuickAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
                currentPosition = position;
                TopUp topUpResponse=(TopUp)adapter.getItem(position);
                if (topUpResponse != null) {
                    rechageMoney.setText(topUpResponse.money);
                    topUpAdapter.notifyDataSetChanged();
                }
            }
        });
        topUpAdapter.setItemSelectedCallBack(new TopUpAdapter.ItemSelectedCallBack() {
            @Override
            public void convert(BaseViewHolder holder, int position) {
                LinearLayout linearLayout = (LinearLayout) holder.getView(R.id.main_topup);
                if (position ==currentPosition){
                    linearLayout.setBackgroundResource(R.drawable.bg_recharge_select);
                }else{
                    linearLayout.setBackgroundResource(R.drawable.bg_recharge_select_un);
                }

            }
        });
    }

    @Override
    public void initData() {
    }


    private void getTopUp() {
        if (topUpList != null) {
            topUpList.clear();
        }
        XHttpRequest.getInstance().postRequests(Url.TOPUP, "", new XHttpRequest.XCallBack() {
            @Override
            public void onResponse(String response) {
                if (!StringUtils.isEmpty(response)) {
                    String status = JsonUtils.getJsonStr(response, Constant.STATUS);
                    if (Constant.DATASUCCESS.equals(status)) {

                        String data = JsonUtils.getJsonStr(response, "data");
                        if (!StringUtils.isEmpty(data)) {
                            List<TopUp> list = JsonUtils.jsonStrToList(data, new TypeToken<ArrayList<TopUp>>() {
                            }.getType());
                            if (list != null && list.size() > 0) {
                                topUpList.addAll(list);
                                topUpAdapter.setNewData(topUpList);
                                rechageMoney.setText(topUpList.get(0).money);
                                mRecyclerView.setVisibility(View.VISIBLE);
                            } else {
                                mRecyclerView.setVisibility(View.GONE);
                            }
                        }
                    }
                }
            }

            @Override
            public void failedRequest(String result) {
                ToastUtil.showToast(getString(R.string.net_error));
            }
        });
    }

    @OnClick({R.id.back, R.id.cb_zfb, R.id.clickZfb, R.id.cb_wx, R.id.click_wx, R.id.click_pay})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.back:
                finish();
                break;
            case R.id.cb_zfb:
                changeType(2);
                break;
            case R.id.clickZfb:
                changeType(2);
                break;
            case R.id.cb_wx:
                changeType(1);
                break;
            case R.id.click_wx:
                changeType(1);
                break;
            case R.id.click_pay:
                if (StringUtils.isEmpty(SPUtils.getInstance().getString("card"))) {
                    Intent intent = new Intent(RechargeActivity.this, AuthActivity.class);
                    Bundle bundle = new Bundle();
                    bundle.putString("isBackAuth", "1");
                    intent.putExtras(bundle);
                    startActivity(intent);
                    return;
                }

                if (cbWx.isChecked()) {
                    startWxPay();
                } else if (cbZfb.isChecked()) {
                    startZfbPay();
                }
                break;
            default:
                break;
        }

    }


    private void changeType(int what) {
        if (1 == what) {
            type = "1";
            cbWx.setChecked(true);
            cbZfb.setChecked(false);
        } else {
            type = "2";
            cbWx.setChecked(false);
            cbZfb.setChecked(true);
        }

    }


    //用微信支付
    private void startWxPay() {
        showLoadingDialog(getResources().getString(R.string.paying));
        JsonObject pay = new JsonObject();
        if (!StringUtils.isEmpty(SPUtils.getInstance().getString("member_id"))) {
            pay.addProperty("member_id", SPUtils.getInstance().getString("member_id"));
        }
        pay.addProperty("payment_mode", "2");//支付方式（必传）1余额，2微信，3支付宝，4银行卡
        pay.addProperty("money", rechageMoney.getText().toString());
        pay.addProperty("type", "1");//支付类型（必传）1账户充值，2缴纳押金，3订单支付，4缴纳罚款
        if (!StringUtils.isEmpty(SPUtils.getInstance().getString("area_id"))) {
            pay.addProperty("area_id", SPUtils.getInstance().getString("area_id"));
        }
        XHttpRequest.getInstance().postRequests(Url.PAY, pay.toString(), new XHttpRequest.XCallBack() {
            @Override
            public void onResponse(String result) {
                if (!StringUtils.isEmpty(result)) {
                    try {
                        final JSONObject jsonObject = new JSONObject(result);
                        if (null != jsonObject && !isFinishing()) {
                            if (Constant.DATASUCCESS.equals(jsonObject.optString("status"))) {
                                dismissLoadingDialog();
                                IWXAPI msgApi = WXAPIFactory.createWXAPI(RechargeActivity.this, Constant.WXAppID, true);
                                if (!msgApi.isWXAppInstalled()) {
                                    ToastUtil.showToast(getString(R.string.wx_installed));
                                }
                                PayReq payReq = new PayReq();
                                payReq.appId = jsonObject.getJSONObject("data").getString("appid");
                                payReq.partnerId = jsonObject.getJSONObject("data").getString("partnerid");
                                payReq.prepayId = jsonObject.getJSONObject("data").getString("prepayid");
                                payReq.packageValue = jsonObject.getJSONObject("data").getString("package");
                                payReq.nonceStr = jsonObject.getJSONObject("data").getString("noncestr");
                                payReq.timeStamp = jsonObject.getJSONObject("data").getString("timestamp");
                                payReq.extData = "RechargePay";
                                payReq.sign = jsonObject.getJSONObject("data").getString("sign");
                                msgApi.sendReq(payReq);
                            } else if ("1001".equals(jsonObject.optString("status"))) {
                                dismissLoadingDialog();
                                ToastUtil.showToast(jsonObject.optString("message"));//账户余额不足

                            }

                        }
                    } catch (Exception e) {
                        dismissLoadingDialog();
                        e.printStackTrace();
                    }
                }
            }

            @Override
            public void failedRequest(String result) {
                dismissLoadingDialog();
                ToastUtil.showToast(getString(R.string.net_error));
            }
        });
    }

    //用支付宝支付
    private void startZfbPay() {
        showLoadingDialog(getString(R.string.paying));
        JsonObject pay = new JsonObject();
        if (!StringUtils.isEmpty(SPUtils.getInstance().getString("member_id"))) {
            pay.addProperty("member_id", SPUtils.getInstance().getString("member_id"));
        }
        pay.addProperty("payment_mode", "3");//支付方式（必传）1余额，2微信，3支付宝，4银行卡
        pay.addProperty("money", rechageMoney.getText().toString());
        pay.addProperty("type", "1");//支付类型（必传）1账户充值，2缴纳押金，3订单支付，4缴纳罚款
        if (!StringUtils.isEmpty(SPUtils.getInstance().getString("area_id"))) {
            pay.addProperty("area_id", SPUtils.getInstance().getString("area_id"));
        }
        XHttpRequest.getInstance().postRequests(Url.PAY, pay.toString(), new XHttpRequest.XCallBack() {
            @Override
            public void onResponse(String result) {
                if (!StringUtils.isEmpty(result)) {
                    try {
                        final JSONObject jsonObject = new JSONObject(result);
                        if (null != jsonObject && !isFinishing()) {
                            if (Constant.DATASUCCESS.equals(jsonObject.optString("status"))) {
                                dismissLoadingDialog();
                                if (!MyUtil.checkAliPayInstalled(RechargeActivity.this)) {
                                    ToastUtil.showToast(getString(R.string.zfb_installed));
                                }
                                Runnable payRunnable = new Runnable() {
                                    @Override
                                    public void run() {
                                        try {
                                            PayTask alipay = new PayTask(RechargeActivity.this);
                                            final Map<String, String> res = alipay.payV2(jsonObject.optJSONObject("data").getString("contents"), true);
                                            runOnUiThread(new Runnable() {
                                                @Override
                                                public void run() {
                                                    PayResult payResult = new PayResult(res);
                                                    String resultInfo = payResult.getResult();
                                                    String resultStatus = payResult.getResultStatus();
                                                    if ("9000".equals(resultStatus)) {
                                                        ToastUtil.showToast(getString(R.string.pay_success));
                                                        EventBus.getDefault().post(EventBusConstants.REFRESH_WALLET_LIST);
                                                        finish();
                                                    } else {
                                                        ToastUtil.showToast(getString(R.string.pay_failed));
                                                    }
                                                }
                                            });
                                        } catch (Exception e) {
                                            e.printStackTrace();
                                        }
                                    }

                                };

                                Thread payThread = new Thread(payRunnable);
                                payThread.start();
                            } else {
                                dismissLoadingDialog();
                                ToastUtil.showToast(jsonObject.optString("message"));//账户余额不足

                            }
                        }
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
            }

            @Override
            public void failedRequest(String result) {
                dismissLoadingDialog();
                ToastUtil.showToast(getString(R.string.net_error));
            }
        });
    }
}
